package CaesarCipher;

import java.util.HashMap;
import java.util.Map;

public class BruteForceAttack {

    // 穷举攻击方法
    public String bruteForce(String ciphertext, String originalText) {
        CaesarCipher cipher = new CaesarCipher();
        Map<Character, Integer> originalFreq = cipher.countFrequency(originalText);
        int bestShift = -1;
        double bestScore = Double.MAX_VALUE;

        for (int shift = 0; shift < 26; shift++) {
            String decryptedText = cipher.decrypt(ciphertext, shift);
            Map<Character, Integer> decryptedFreq = cipher.countFrequency(decryptedText);
            double score = calculateScore(originalFreq, decryptedFreq);

            if (score < bestScore) {
                bestScore = score;
                bestShift = shift;
            }
        }

        return cipher.decrypt(ciphertext, bestShift);
    }

    // 计算频率匹配得分
    private double calculateScore(Map<Character, Integer> originalFreq, Map<Character, Integer> decryptedFreq) {
        double score = 0.0;
        for (Map.Entry<Character, Integer> entry : originalFreq.entrySet()) {
            char ch = entry.getKey();
            int originalCount = entry.getValue();
            int decryptedCount = decryptedFreq.getOrDefault(ch, 0);
            score += Math.abs(originalCount - decryptedCount);
        }
        return score;
    }
}
